﻿#region Old

//using YougeBookmark.Business.Services;
//using YougeBookmark.DataAccess;
//using YougeBookmark.Models;
//using System.Windows.Forms;

//namespace YougeBookmark.Forms;

///// <summary>
///// 主窗体类
///// </summary>
//public partial class MainForm : Form
//{
//    private readonly BookmarkService _bookmarkService;
//    private int _currentPage = 1;
//    private const int PageSize = 20;

//    /// <summary>
//    /// 构造函数（依赖注入）
//    /// </summary>
//    public MainForm(BookmarkService bookmarkService)
//    {
//        _bookmarkService = bookmarkService;
//        InitializeComponent();
//        InitializeDataGrid();  // 初始化数据表格列
//        LoadData();            // 加载初始数据
//    }

//    /// <summary>
//    /// 加载分页数据
//    /// </summary>
//    private void LoadData()
//    {
//        // 调用服务层获取数据
//        var (items, total) = _bookmarkService.GetPaged(_currentPage, PageSize, null, null, new());

//        // 绑定数据源
//        dataGridView.DataSource = items;
//        UpdatePagingControls(total);
//    }

//    /// <summary>
//    /// 更新分页控件状态
//    /// </summary>
//    private void UpdatePagingControls(int total)
//    {
//        // 计算总页数
//        var totalPages = (total + PageSize - 1) / PageSize;
//        lblPage.Text = $"第 {_currentPage} 页 / 共 {totalPages} 页";

//        // 按钮状态控制
//        btnPrev.Enabled = _currentPage > 1;
//        btnNext.Enabled = _currentPage < totalPages;
//    }

//    // 点击添加按钮事件
//    private void btnAdd_Click(object sender, EventArgs e)
//    {
//        // 显示书签编辑窗体
//        using var form = new BookmarkForm(null,null);//?
//        if (form.ShowDialog() == DialogResult.OK)
//        {
//            LoadData();  // 保存成功后刷新数据
//        }
//    }

//    // 在MainForm.cs中添加以下事件处理方法
//    private void btnPrev_Click(object sender, EventArgs e)
//    {
//        if (_currentPage > 1)
//        {
//            _currentPage--;
//            LoadData();
//        }
//    }

//    private void btnNext_Click(object sender, EventArgs e)
//    {
//        _currentPage++;
//        LoadData();
//    }

//    private void btnSearch_Click(object sender, EventArgs e)
//    {
//        // 实现搜索逻辑
//        _currentPage = 1;
//        LoadData();
//    }

//    // 在 MainForm.cs 类中添加以下方法
//    private void InitializeDataGrid()
//    {
//        // 清除自动生成列
//        dataGridView.AutoGenerateColumns = false;
//        dataGridView.RowTemplate.Height = 30;
//        dataGridView.AllowUserToResizeRows = false;
//        dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

//        // 创建自定义列
//        var columns = new DataGridViewColumn[]
//        {
//        new DataGridViewTextBoxColumn
//        {
//            HeaderText = "ID",
//            DataPropertyName = "Id",
//            Width = 50,
//            ReadOnly = true,
//            DefaultCellStyle = new DataGridViewCellStyle { ForeColor = Color.Gray }
//        },
//        new DataGridViewLinkColumn
//        {
//            HeaderText = "网址",
//            DataPropertyName = "Url",
//            Width = 250,
//            LinkBehavior = LinkBehavior.SystemDefault,
//            TrackVisitedState = true,
//            LinkColor = Color.Blue
//        },
//        new DataGridViewTextBoxColumn
//        {
//            HeaderText = "备注",
//            DataPropertyName = "Remark",
//            Width = 150,
//            DefaultCellStyle = new DataGridViewCellStyle { WrapMode = DataGridViewTriState.True }
//        },
//        new DataGridViewTextBoxColumn
//        {
//            HeaderText = "标签",
//            DataPropertyName = "Tags",
//            Width = 200,
//            Tag = "Tags", // 用于后续识别特殊处理
//            DefaultCellStyle = new DataGridViewCellStyle
//            {
//                ForeColor = Color.White,
//                BackColor = Color.FromArgb(76, 175, 80) // 默认标签颜色
//            }
//        },
//        new DataGridViewTextBoxColumn
//        {
//            HeaderText = "创建时间",
//            DataPropertyName = "CreatedAt",
//            Width = 150,
//            DefaultCellStyle = new DataGridViewCellStyle
//            {
//                Format = "yyyy-MM-dd HH:mm",
//                Alignment = DataGridViewContentAlignment.MiddleCenter
//            }
//        }
//    };

//        // 添加列并配置样式
//        dataGridView.Columns.AddRange(columns);

//        // 配置网格样式
//        dataGridView.EnableHeadersVisualStyles = false;
//        dataGridView.ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
//        {
//            BackColor = Color.FromArgb(51, 51, 51),
//            ForeColor = Color.White,
//            Font = new Font("微软雅黑", 9, FontStyle.Bold)
//        };

//        dataGridView.AlternatingRowsDefaultCellStyle = new DataGridViewCellStyle
//        {
//            BackColor = Color.FromArgb(240, 240, 240)
//        };

//        // 绑定点击事件
//        dataGridView.CellContentClick += (sender, e) =>
//        {
//            if (dataGridView.Columns[e.ColumnIndex] is DataGridViewLinkColumn && e.RowIndex != -1)
//            {
//                var url = dataGridView.Rows[e.RowIndex].Cells["Url"].Value.ToString();
//                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true });
//            }
//        };

//        // 自定义标签显示格式
//        dataGridView.CellFormatting += (sender, e) =>
//        {
//            if (dataGridView.Columns[e.ColumnIndex].Tag?.ToString() == "Tags")
//            {
//                if (e.Value is string tagIds)
//                {
//                    var tagService = new TagService(new AppDbContext());
//                    var tags = tagIds.Split(',').Select(id =>
//                        tagService.GetTagNameById(int.Parse(id))).ToList();

//                    e.Value = string.Join(", ", tags);
//                    e.FormattingApplied = true;
//                }
//            }
//        };
//    }

//}

#endregion Old

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using YougeBookmark.Business.Services;
using YougeBookmark.DataAccess;
using YougeBookmark.Models;

namespace YougeBookmark.Forms
{
    public partial class MainForm : Form
    {
        private readonly BookmarkService _bookmarkService; // 书签服务实例
        private readonly TagService _tagService;           // 标签服务实例
        private int _currentPage = 1;                      // 当前页码
        private const int PageSize = 20;                   // 每页显示数量

        /// <summary>
        /// 构造函数（依赖注入）
        /// </summary>
        /// <param name="bookmarkService">书签服务</param>
        /// <param name="tagService">标签服务</param>
        public MainForm(BookmarkService bookmarkService, TagService tagService)
        {
            _bookmarkService = bookmarkService;
            _tagService = tagService;

            InitializeComponent();
            InitializeDataGrid();  // 初始化数据表格
            LoadData();            // 加载初始数据
        }

        /// <summary>
        /// 初始化数据表格列和样式
        /// </summary>
        private void InitializeDataGrid()
        {
            // 配置表格基本属性
            dataGridView.AutoGenerateColumns = false;
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            dataGridView.RowTemplate.Height = 30;
            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            // 添加自定义列
            var columns = new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "ID",
                    DataPropertyName = "Id",
                    Width = 50,
                    ReadOnly = true,
                    DefaultCellStyle = new DataGridViewCellStyle { ForeColor = Color.Gray }
                },
                new DataGridViewLinkColumn
                {
                    HeaderText = "网址",
                    DataPropertyName = "Url",
                    Width = 250,
                    LinkBehavior = LinkBehavior.SystemDefault,
                    TrackVisitedState = true,
                    LinkColor = Color.Blue
                },
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "备注",
                    DataPropertyName = "Remark",
                    Width = 150,
                    DefaultCellStyle = new DataGridViewCellStyle { WrapMode = DataGridViewTriState.True }
                },
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "标签",
                    DataPropertyName = "Tags",
                    Width = 200,
                    DefaultCellStyle = new DataGridViewCellStyle
                    {
                        ForeColor = Color.White,
                        BackColor = Color.FromArgb(76, 175, 80) // 默认标签颜色
                    }
                },
                new DataGridViewTextBoxColumn
                {
                    HeaderText = "创建时间",
                    DataPropertyName = "CreatedAt",
                    Width = 150,
                    DefaultCellStyle = new DataGridViewCellStyle
                    {
                        Format = "yyyy-MM-dd HH:mm",
                        Alignment = DataGridViewContentAlignment.MiddleCenter
                    }
                }
            };

            // 添加列并配置样式
            dataGridView.Columns.AddRange(columns);

            // 配置网格样式
            dataGridView.EnableHeadersVisualStyles = false;
            dataGridView.ColumnHeadersDefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = Color.FromArgb(51, 51, 51),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 9, FontStyle.Bold)
            };

            dataGridView.AlternatingRowsDefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = Color.FromArgb(240, 240, 240)
            };

            // 绑定点击事件
            dataGridView.CellContentClick += (sender, e) =>
            {
                if (dataGridView.Columns[e.ColumnIndex] is DataGridViewLinkColumn && e.RowIndex != -1)
                {
                    var url = dataGridView.Rows[e.RowIndex].Cells["Url"].Value.ToString();
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true });
                }
            };
        }

        /// <summary>
        /// 加载分页数据
        /// </summary>
        private void LoadData()
        {
            // 调用服务层获取数据
            var (items, total) = _bookmarkService.GetPaged(_currentPage, PageSize, null, null, new List<int>());

            // 绑定数据源
            dataGridView.DataSource = items;
            UpdatePagingControls(total);
        }

        /// <summary>
        /// 更新分页控件状态
        /// </summary>
        /// <param name="total">总记录数</param>
        private void UpdatePagingControls(int total)
        {
            // 计算总页数
            var totalPages = (int)Math.Ceiling((double)total / PageSize);
            lblPage.Text = $"第 {_currentPage} 页 / 共 {totalPages} 页";

            // 按钮状态控制
            btnPrev.Enabled = _currentPage > 1;
            btnNext.Enabled = _currentPage < totalPages;
        }

        // 点击添加按钮事件
        private void btnAdd_Click(object sender, EventArgs e)
        {
            // 显示书签编辑窗体
            using var form = new BookmarkForm(_bookmarkService, _tagService);
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadData();  // 保存成功后刷新数据
            }
        }

        // 点击上一页按钮事件
        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                LoadData();
            }
        }

        // 点击下一页按钮事件
        private void btnNext_Click(object sender, EventArgs e)
        {
            _currentPage++;
            LoadData();
        }

        // 点击搜索按钮事件
        private void btnSearch_Click(object sender, EventArgs e)
        {
            // 实现搜索逻辑
            _currentPage = 1;
            LoadData();
        }

        // 双击行事件（编辑书签）
        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var bookmarkId = (int)dataGridView.Rows[e.RowIndex].Cells["Id"].Value;
                using var form = new BookmarkForm(_bookmarkService, _tagService, bookmarkId);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    LoadData();  // 保存成功后刷新数据
                }
            }
        }

        // 窗体加载事件
        private void MainForm_Load(object sender, EventArgs e)
        {
            // 初始化窗口状态
            this.Text = $"优哥书签管理 - 版本 {Application.ProductVersion}";
            statusStrip1.Items[0].Text = "就绪";
        }

        // 剪贴板监控事件
        private void clipboardWatcher_ClipboardChanged(object sender, EventArgs e)
        {
            // 自动检测剪贴板中的URL并提示添加
            if (Uri.TryCreate(Clipboard.GetText(), UriKind.Absolute, out var uri))
            {
                if (MessageBox.Show($"检测到新网址：{uri}\n是否要添加到书签？",
                    "添加书签", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    using var form = new BookmarkForm(_bookmarkService, _tagService);
                    form.SetUrl(uri.ToString());
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        LoadData();
                    }
                }
            }
        }
    }
}
